package com.hyj.serve.manage.utils;

import cn.hutool.extra.ssh.JschRuntimeException;
import cn.hutool.extra.ssh.JschUtil;
import com.hyj.serve.manage.configure.exception.ServiceException;
import com.jcraft.jsch.Session;
import lombok.Getter;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HeYuJie
 * @date 2022/6/2
 */
public class SSHClient {

    private static final Map<String, SSHClient> SSH_LIST = new HashMap<>();

    @Getter
    private Session session;

    public static SSHClient getSSHClient(String ip, int port){
        return SSH_LIST.get(ip+":"+port);
    }
    public static SSHClient getSSHClient (String ip, int port, String username, String password){
        SSHClient sshClient = getSSHClient(ip, port);
        if(sshClient == null){
            sshClient = new SSHClient(ip, port, username, password);
            SSH_LIST.put(ip+":"+port, sshClient);
        }
        return sshClient;
    }


    public SSHClient (String ip, int port, String username, String password){
        try {
            session = JschUtil.createSession(ip, port, username, password);
            // 测试连接
            exec("pwd");
        } catch (JschRuntimeException e){
            throw new ServiceException(e, "创建连接失败: ", e.getMessage());
        }
    }

    public String exec(String cmd){
        return JschUtil.exec(session, cmd + " 2>&1", StandardCharsets.UTF_8);
    }

    public void write(String path, String content){
        String b64 = Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8));
        exec("echo \""+b64+"\" |base64 -d > "+path);
    }

}
